import hashlib

from flask import Blueprint, request

bp = Blueprint('wechat_routes', __name__, template_folder="templates")


# 处理微信服务器验证请求
@bp.route('/wechat', methods=['GET'])
def verify():
    token = 'yangjiantoken'  # 替换为你在微信公众号平台设置的 Token
    signature = request.args.get('signature', '')
    timestamp = request.args.get('timestamp', '')
    nonce = request.args.get('nonce', '')
    echostr = request.args.get('echostr', '')

    # 按微信规则将 token、timestamp、nonce 三个参数排序后进行 SHA1 加密
    sorted_params = ''.join(sorted([token, timestamp, nonce]))
    encrypted = hashlib.sha1(sorted_params.encode()).hexdigest()
    print("==signature:", signature)
    print("==nonce:", nonce)
    print("==echostr:", echostr)
    print("==encrypted:", encrypted)

    # 验证请求是否来自微信服务器
    if encrypted == signature:
        return echostr
    else:
        return 'Verification failed!', 403


# 处理微信服务器发送的消息
@bp.route('/wechat', methods=['POST'])
def handle_message():
    # 解析微信服务器发送的 XML 消息
    xml_data = request.data
    # 处理消息逻辑，这里你可以根据自己的需求进行处理
    # 详细处理逻辑可参考微信公众号开发文档

    # 返回一个空字符串表示处理成功
    return ''
